<template>
  <div class="register">
    <div class="headBox">
      <img :src="require('@/assets/images/headLogo.png')" />
      <span>数字化成长空间</span>
    </div>
    <div class="registerBox">
      <div class="backAccountAndCodeLogin">
        <!-- <div class="backLogin" @click="changeBackLogin">返回登录</div>
        <div class="linear" /> -->
        <div class="backAccountLogin" @click="changeBackLogin">
          返回登录
          <img :src="require('@/assets/images/goRegisterIcon.png')" class="goIcon" />
        </div>
      </div>
      <div class="title">快速注册</div>
      <el-form class="apply-form first-form" :model="register.user" :rules="registerRules" ref="register"
        @submit.native.prevent>
        <!-- <el-form-item prop="mPhone">
          <el-input
            type="text"
            v-model="register.user.mPhone"
            :class="{ haveValue: register.user.mPhone }"
            placeholder="请输入手机号"
            @keypress.enter.native.prevent
          ></el-input>
        </el-form-item>
        <el-form-item prop="regName">
          <el-input
            type="text"
            v-model="register.user.regName"
            :class="{ haveValue: register.user.regName }"
            placeholder="请输入用户名"
            @keypress.enter.native.prevent
          ></el-input>
        </el-form-item> -->
        <el-form-item prop="email" :error="emailErrorMessage">
          <el-input id="r_email" type="text" v-model="register.user.email" :class="{ haveValue: register.user.email }"
            placeholder="请输入邮箱" @keypress.enter.native.prevent @change="handleChangeEmail"></el-input>
        </el-form-item>
        <el-form-item prop="code" :error="codeErrorMessage">
          <el-input type="text" placeholder="请输入获取的验证码" v-model="register.user.code"
            :class="{ haveValue: register.user.code }" @keypress.enter.native.prevent></el-input>
          <div class="fetchCodeBox">
            <button class="fetchCode" @click.prevent="checkEmailField" tabindex="-1">
              {{ codeLastTime ? codeLastTime + "秒" : "获取验证码" }}
            </button>
          </div>
          <div class="codeTips" v-show="showCodeTips">验证码已发送至邮箱</div>
        </el-form-item>

        <el-form-item prop="realName">
          <el-input id="r_realName" v-model="register.user.realName"
            :class="{ haveValue: register.user.realName }" placeholder="请输入真实姓名"
            @keypress.enter.native.prevent></el-input>
        </el-form-item>
        <el-form-item prop="mPhone">
          <el-input id="r_mPhone" type="tel" v-model="register.user.mPhone"
            :class="{ haveValue: register.user.mPhone }" placeholder="请输入手机号码"
            @keypress.enter.native.prevent></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input id="r_password" type="password" v-model="register.user.password"
            :class="{ haveValue: register.user.password }" placeholder="请输入密码" show-password
            @keypress.enter.native.prevent></el-input>
        </el-form-item>
        <el-form-item prop="rpassword" class="lastInput">
          <el-input type="password" v-model="register.user.rpassword" :class="{ haveValue: register.user.rpassword }"
            placeholder="请确认密码" @keypress.enter.native.prevent></el-input>
        </el-form-item>



        <el-form-item prop="roleFlag" class="userSelectType">
          <div class="checkBoxTitle">用户类型：</div>
          <el-checkbox-group v-model="register.user.roleFlag" @keypress.enter.native.prevent>
            <el-checkbox :label="1" name="roleFlag" class="first-checkBox">学生</el-checkbox>
            <el-checkbox :label="2" name="roleFlag">教师</el-checkbox>
            <el-checkbox :label="8" name="roleFlag">家长</el-checkbox>
            <!-- <el-checkbox :label="16" name="roleFlag">用人单位</el-checkbox>
            <el-checkbox :label="32" name="roleFlag">企业导师</el-checkbox> -->

          </el-checkbox-group>
        </el-form-item>
        <el-form-item class="agreementAndprivacyPolicy" prop="agreement">
          <el-checkbox-group v-model="register.user.agreement" @keypress.enter.native.prevent>
            <el-checkbox name="agreement">
              <div slot>
                同意<span @click.prevent class="agreementLink"
                  @click="showRegistrationAgreement = true">《数字化成长空间注册协议》</span>和<span @click.prevent
                  class="agreementLink" @click="showPrivacyPolicy = true">《隐私政策》</span>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="loginBtn" :loading="load" @click="verificationValue"
            :disabled="loging">立即注册</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="《注册协议》" top="4vh" :visible.sync="showRegistrationAgreement" width="50vw"
      custom-class="showRegistrationAgreement">
      <regAgreement />>
    </el-dialog>
    <el-dialog title="《隐私政策》" top="4vh" :visible.sync="showPrivacyPolicy" width="50vw" custom-class="showPrivacyPolicy">
      <regPrivacy />
    </el-dialog>
  </div>
</template>

<script>
import {
  register,
  sendVaildCode,
  checkVaildCode,
  isExist,
} from "@/request/user";
import { throttle, location } from "@/util/tool";
import md5 from "js-md5";
import regAgreement from "@/views/user/register/regAgreement";
import regPrivacy from "@/views/user/register/regPrivacy";
export default {
  // 组件销毁前清除定时器
  beforeDestroy() {
    clearInterval(this.lastTimer);
  },
  components: {
    regAgreement,
    regPrivacy,
  },
  data() {
    let phomeReg =
      /^1(?:70\d|(?:9[89]|8[0-24-9]|7[135-8]|66|5[0-35-9])\d|3(?:4[0-8]|[0-35-9]\d))\d{7}$/;
    var validatemPhone = (rule, value, callback) => {
      if (!phomeReg.test(value)) {
        callback(new Error("请输入11位，正确的手机号！"));
      } else {
        callback();
      }
    };
    let pwdReg =
      /(?=.*([a-zA-Z].*))(?=.*[0-9].*)[a-zA-Z0-9-*/+.~!@#$%^&*()]{6,20}$/;
    var validatePassword = (rule, value, callback) => {
      if (!pwdReg.test(value)) {
        callback(
          new Error("请输入6-20位，必须包含数字与字母、或符号的有效密码！")
        );
      } else {
        callback();
      }
    };
    var validateRepeatPwd = (rule, value, callback) => {
      if (this.register.user.password !== value) {
        callback(new Error("两次密码不一致！"));
      } else {
        callback();
      }
    };

    const mailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    var checkEmail = (rule, value, callback) => {
      // 如果已经验证过 邮箱已被注册 则返回
      if (this.checkEmail === false) {
        this.emailErrorMessage = "";
        this.$nextTick(() => {
          callback(
            new Error(
              this.errState === 1 ? "邮箱已被注册" : "账号验证失败，请重新输入!"
            )
          );
        });
        return;
      }

      if (!mailReg.test(value)) {
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };

    return {
      // 验证码登录参数
      register: {
        user: {
          regName: "", // 用户名
          realName:"",
          mPhone: "", // 手机号
          email: "", // 账号
          code: "", // 验证码
          password: "", // 密码
          rpassword: "", // 重复密码
          iconPath: "/iconPath.png", // 头像
          nickName: "", //
          roleFlag: [],
          // roleFlag: "",
          agreement: [],
        },
      },
      // 注册信息验证
      registerRules: {
        mPhone: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur",
          },
          {
            validator: validatemPhone,
            trigger: "blur",
          },
        ],
        regName: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
        realName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: "blur",
          },
        ],
        email: [
          {
            required: true,
            message: "请输入邮箱地址",
            trigger: "blur",
          },
          {
            validator: checkEmail,
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
          {
            validator: validatePassword,
            trigger: "change",
          },
          {
            validator: validatePassword,
            trigger: "blur",
          },
        ],
        rpassword: [
          {
            required: true,
            message: "请确认密码",
            trigger: "blur",
          },
          {
            validator: validateRepeatPwd,
            trigger: "change",
          },
          {
            validator: validateRepeatPwd,
            trigger: "blur",
          },
        ],
        roleFlag: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个用户类型",
            trigger: "change",
          },
        ],
        agreement: [
          {
            type: "array",
            required: true,
            message: "请阅读并勾选同意",
            trigger: "change",
          },
        ],
      },
      codeErrorMessage: "", // 验证码错误提示
      load: false,
      loging: false, // 防止控制多次请求
      codeLastTime: 0, // 倒计时
      lastTimer: null, // 定时器
      showCodeTips: false, // 显示已发送验证码提示
      showPrivacyPolicy: false,
      showRegistrationAgreement: false,
      emailErrorMessage: "", // 邮箱验证信息
      errState: 0,
      checkEmail: null,
      userIconList: [
        location(window) + "/icons/user/icon1.png",
        location(window) + "/icons/user/icon2.png",
        location(window) + "/icons/user/icon3.png",
        location(window) + "/icons/user/icon4.png",
        location(window) + "/icons/user/icon5.png",
        location(window) + "/icons/user/icon6.png",
        location(window) + "/icons/user/icon7.png",
        location(window) + "/icons/user/icon8.png",
        location(window) + "/icons/user/icon9.png",
        location(window) + "/icons/user/icon10.png",
        location(window) + "/icons/user/icon11.png",
        location(window) + "/icons/user/icon12.png",
        location(window) + "/icons/user/icon13.png",
        location(window) + "/icons/user/icon14.png",
        location(window) + "/icons/user/icon15.png",
      ],
    };
  },
  created() {
    this.handleGetLastTime();
  },
  methods: {
    // 设置发送验证码剩余时间
    handleGetLastTime() {
      let sendRegCodeLastTime = localStorage.getItem("sRCLT");
      const currTime = new Date().getTime();
      if (sendRegCodeLastTime === null) {
        this.codeLastTime = 0;
        return;
      }
      if (currTime - sendRegCodeLastTime < 60000) {
        this.handelFetchCode(
          60 - Math.ceil((currTime - sendRegCodeLastTime) / 1000)
        );
      } else {
        localStorage.removeItem("sRCLT");
      }
    },
    // 验证码计时器
    handelFetchCode(time) {
      this.showCodeTips = true;
      // 如果验证码已发送倒计时没结束则退出
      this.codeLastTime = time;
      this.lastTimer = setInterval(() => {
        --this.codeLastTime;
        // 清除计时器
        if (this.codeLastTime === 0) {
          clearInterval(this.lastTimer);
          this.lastTimer = null;
          localStorage.removeItem("sRCLT");
        }
      }, 1000);
    },
    // 验证邮箱字段
    checkEmailField() {
      this.$refs["register"].validateField("email", (res) => {
        this.emailErrorMessage = "";
        if (this.checkEmail === false) {
          this.$nextTick(() => {
            this.emailErrorMessage =
              this.errState === 1
                ? "邮箱已被注册"
                : "账号验证失败，请重新输入!";
          });
        } else {
          // 如果返回的错误信息为空
          if (res === "") {
            this.sendCode();
          }
        }
      });
    },
    // 验证参数
    verificationValue() {
      this.$refs["register"].validate((valid) => {
        if (valid) {
          this.checkCode();
        } else {
          return false;
        }
      });
    },
    // 注册
    handelRegister() {
      this.load = true;
      this.loging = true;
      let params = {};
      params = Object.assign({}, this.register.user);
      params.password = md5(params.password);
      params.roleFlag = params.roleFlag.reduce(
        (acc, val) => Number(acc) + Number(val),
        0
      );
      params.iconPath =
        this.userIconList[parseInt(Math.random() * (14 + 1), 10)] ||
        location(window) + "/icons/user/icon1.png";

      // params.code = undefined;
      params.regName = this.register.user.realName;
      // params.mPhone = undefined;
      params.rpassword = undefined;
      params.agreement = undefined;
      // params.email = undefined // email为空字符串时服务器会报错
      if (params.email == "" || params.password == "") {
        this.$message({
          message: "邮箱或密码不能为空",
          type: "error",
        });
        return;
      }
      params.userdetail = { realName: this.register.user.realName}
      //   userName: params.user.email,
      //   password: params.user.password,
      // });
      register(params).then(async (res) => {
        this.load = false;
        this.loging = false;
        if (res.errno === 0) {
          // 清空表单
          // this.$refs.register.resetFields();
          this.$antdMessage.success({
            content: "注册成功",
          });
          // todo 注册成功后需要马上调用登录接口 不然没有coookie
          await this.$store.dispatch("user/Login", {
            params: {
              userName: params.user.email,
              password: params.user.password,
            },
            this: this,
          });
          if (this.$refs?.register) this.$refs.register.resetFields();
          const routerParams = this.$router.currentRoute.params;
          if (routerParams.rediretUrl) return window.location.href = routerParams.rediretUrl
          if (routerParams.routePath || routerParams.query) {
            return this.$router.replace({
              path: routerParams.routePath,
              query: routerParams?.query,
            });
          } else {
            this.$router.go(-1)
            // this.$router.replace({ name: "Home" });
          }
        } else {
          this.$antdMessage.error({
            content: res.message,
          });
        }
      });
    },
    // 返回登录
    changeBackLogin() {
      this.$router.push({ name: "Login" });
    },
    // 发送验证码
    sendCode() {
      // // 查看剩余时间
      if (this.codeLastTime) return;
      const params = { userMail: this.register.user.email, toFindPwd: true };
      sendVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.$antdMessage.success({
            content: `验证码已发送至邮箱，验证码有效时间${
              res.data.duration / 60
            }分钟！`,
          });
          localStorage.setItem("sRCLT", new Date().getTime());
          this.handelFetchCode(60);
        } else {
          this.$antdMessage.error({
            content: res.message || res,
          });
        }
      });
    },
    // 验证验证码是否正确
    checkCode() {
      if (this.checkEmail === false) {
        this.emailErrorMessage = "";
        this.$nextTick(() => {
          this.emailErrorMessage = this.errState === 1 ? "邮箱已被注册" : "账号验证失败，请重新输入!";
        });
        return;
      }
      // 先清空错误提示 否则多次错误无法显示错误信息
      this.codeErrorMessage = "";
      const params = {
        userMail: this.register.user.email,
        code: Number(this.register.user.code),
      };
      checkVaildCode(params).then((res) => {
        if (res.errno === 0) {
          this.handelRegister();
        } else if (res.message === "验证码已失效！") {
          this.$nextTick(() => {
            this.codeErrorMessage = res.message || "验证码错误";
          });
        } else {
          this.$antdMessage.error({
            content: res.message,
          });
        }
      });
    },
    // 输入邮箱
    handleChangeEmail() {
      this.checkEmail = null;
      // 验证邮箱字段
      this.$refs["register"].validateField("email", (res) => {
        // 如果返回的错误信息为空
        if (res === "") {
          throttle(() => {
            this.emailErrorMessage = "";
            this.errState = 0;
            this.checkAccountNum({
              userName: this.register.user.email,
            }).then((isPass) => {
              if (isPass === "pass") {
                this.emailErrorMessage = "";
                this.checkEmail = true;
                return;
              }
              if (isPass === "notpass") {
                this.emailErrorMessage = "邮箱已被注册";
                this.checkEmail = false;
                this.errState = 1;
              }
              if (isPass === "err") {
                this.emailErrorMessage = "账号验证失败，请重新输入!";
                this.checkEmail = false;
                this.errState = 2;
              }
            });
          });
        }
      });
    },
    // 检查邮箱是否被使用
    checkAccountNum(data) {
      return new Promise((resvloe, reject) => {
        isExist(data)
          .then((res) => {
            if (res.message && res.message === "用户名未存在") {
              resvloe("pass");
            } else {
              resvloe("notpass");
            }
          })
          .catch((err) => {
            resvloe("err");
          });
      });
    },
  },
};
</script>

<style lang="stylus">
.register {
  padding-bottom: 22px;
  height: 800px;
  // height: calc(100vh - 60px - 14px);
  background: #fffdfc;

  .headBox {
    padding-top: 50px;
    // margin: 0 auto;
    // width: 425px;
    text-align: center;
    font-family: Segoe UI;
    font-size: 18px;
    font-weight: bold;
    color: #707070;

    img {
      margin-left: 80px;
      width: 59px;
      height: 53px;
    }

    span {
      margin-left: 53px;
    }
  }

  .registerBox {
    padding: 38px 51px 0 54px;
    margin: 47px auto 0;
    position: relative;
    width: 425px;
    height: 606;
    background-color: #ffffff;
    border-radius: 5px;
    border: solid 1px #d9d7d7;

    .backAccountAndCodeLogin {
      position: absolute;
      top: 25px;
      right: 28px;
      display: flex;
      align-items: center;
      font-family: Segoe UI;
      font-size: 14px;
      color: #0e79c0;

      .linear {
        margin: 0 13px;
        width: 1px;
        height: 16px;
        background: #0e79c0;
        opacity: 0.5;
      }

      .backLogin {
        cursor: pointer;
      }

      .backAccountLogin {
        z-index: 10;
        cursor: pointer;
        display: flex;
        align-items: center;

        .goIcon {
          margin-left: 10px;
          width: 15px;
          height: 15px;
        }
      }
    }

    .title {
      margin-bottom: 35px;
      position: relative;
      text-align: center;
      font-family: Segoe UI;
      font-weight: bold;
      font-size: 20px;
      color: #0e79c0;
    }

    .title:after {
      position: absolute;
      content: '';
      left: 50%;
      right: 50%;
      bottom: -4px;
      width: 20px;
      height: 4px;
      background: #0e79c0;
      border-radius: 8px;
      transform: translate(-50%, 0);
    }

    .el-form {
      .el-form-item {
        margin-bottom: 25px;

        .el-form-item__content {
          line-height: 1;
          position: relative;

          .el-input {
            .el-input__inner {
              background: #ececec;
              border-color: #ececec;
              font-family: Segoe UI;
              font-size: 14px;
              color: #707070;
            }

            .el-input__inner:focus {
              background: #fbf9b8;
            }
          }

          .haveValue {
            .el-input__inner {
              background: #fbf9b8;
            }
          }

          .el-checkbox-group {
            line-height: 1;

            .el-checkbox {
              margin-right: 10px;
              line-height: 1;

              .el-checkbox__label {
                padding-left: 5px;
                font-family: Segoe UI;
                font-size: 14px;
                color: #707070;
                opacity: 0.6;
              }

              .el-checkbox__inner {
                position: relative;
                border-color: #eaeef3;
                background: #eaeef3;
              }

              .el-checkbox__inner::after {
                display: block;
                box-sizing: content-box;
                content: '';
                border: 2px solid #FFF;
                border-left: 0;
                border-top: 0;
                height: 7px;
                left: 4px;
                position: absolute;
                top: 1px;
                transform: rotate(45deg) scaleY(1);
                width: 3px;
                transition: transform 0.15s ease-in 0.05s;
                transform-origin: center;
              }

              .is-checked {
                .el-checkbox__inner {
                  border-color: #75c42e;
                  background: #75c42e;
                }
              }
            }

            .first-checkBox {
              margin-left: 80px;
            }

            .second-checkBox {
              margin-right: 0;
            }
          }

          .checkBoxTitle {
            position: absolute;
            line-height: 1;
            left: 0;
            top: 0;
            font-family: Segoe UI;
            font-size: 14px;
            color: #707070;
          }

          .loginBtn {
            width: 320px;
            height: 48px;
            background-color: #0e79c0;
            border-radius: 25px;
          }

          .el-radio-group {
            .el-radio {
              .el-radio__input {
                .el-radio__inner {
                  width: 14px;
                  height: 14px;
                  border-radius: 2px;
                  border-color: #eaeef3;
                  background: #eaeef3;
                }

                .el-radio__inner::after {
                  display: block;
                  box-sizing: content-box;
                  content: '';
                  border: 2px solid #FFF;
                  border-left: 0;
                  border-top: 0;
                  background: unset;
                  height: 7px;
                  left: 4px;
                  position: absolute;
                  top: 1px;
                  transform: rotate(45deg) scaleY(1);
                  width: 3px;
                  transition: transform 0.15s ease-in 0.05s;
                  transform-origin: center;
                }
              }

              .is-checked {
                .el-radio__inner {
                  background: #75c42e;
                }
              }

              .el-radio__label {
                font-family: Segoe UI;
                font-size: 14px;
                color: #707070;
                opacity: 0.6;
              }
            }
          }
        }
      }

      .userSelectType {
        margin-bottom: 14px;

        .radioTitle {
          position: absolute;
          line-height: 1;
          left: 0;
          top: 0;
          font-family: Segoe UI;
          font-size: 14px;
          color: #707070;
        }

        .el-radio {
          margin-right: 10px;

          .el-radio__label {
            padding-left: 5px;
          }
        }

        .first-radioBox {
          margin-left: 80px;
        }

        .second-checkBox {
          margin-right: 0;
        }
      }

      .agreementAndprivacyPolicy {
        margin-bottom: 20px;

        .el-form-item__content {
          .el-checkbox {
            margin-right: 10px;
            line-height: 1;

            .el-checkbox__label {
              padding-left: 5px;

              div {
                font-family: Segoe UI;
                font-size: 12px;
                color: #707070;

                .agreementLink {
                  font-family: Segoe UI;
                  font-size: 12px;
                  color: #0e79c0;
                }
              }
            }

            .el-checkbox__inner {
              position: relative;
              border-color: #eaeef3;
              background: #eaeef3;
            }

            .el-checkbox__inner::after {
              display: block;
              box-sizing: content-box;
              content: '';
              border: 2px solid #FFF;
              border-left: 0;
              border-top: 0;
              height: 7px;
              left: 4px;
              position: absolute;
              top: 1px;
              transform: rotate(45deg) scaleY(1);
              width: 3px;
              transition: transform 0.15s ease-in 0.05s;
              transform-origin: center;
            }

            .is-checked {
              .el-checkbox__inner {
                border-color: #75c42e;
                background: #75c42e;
              }
            }
          }
        }
      }

      .lastInput {
        margin-bottom: 20px;
      }
    }

    .fetchCodeBox {
      position: absolute;
      right: 8px;
      top: 10px;
      height: 20px;
      line-height: 20px;

      button {
        cursor: pointer;
        padding: 0;
        padding-left: 6px;
        min-width: 77px;
        text-align: center;
        outline: none;
        height: 20px;
        line-height: 20px;
        border: none;
        border-left: 1px dashed #909090;
        background: transparent;
        font-family: Segoe UI;
        font-size: 14px;
        color: #0e79c0;
        opacity: 0.6;
      }
    }

    .codeTips {
      bottom: -15px;
      position: absolute;
      right: 0;
      font-size: 12px;
      color: #707070;
    }
  }

  .showRegistrationAgreement, .showPrivacyPolicy {
    .el-dialog__header {
      text-align: center;
    }

    .el-dialog__body {
      padding-top: 0;
    }
  }
}
</style>